package mqttClient

import (
	"encoding/json"
	"errors"
	"github.com/parnurzeal/gorequest"
	"gitee.com/yuyuaa/wensGoMqtt.git/common"
	"log"
	"strings"
	"time"
)

//实现http转发到本地
func (self *Client) setupHttpBridge() {
	type Result struct {
		Status string      `json:"status"`
		Data   interface{} `json:"data"`
		Msg    string      `json:"msg"`
	}
	//topic := "/{{clientId}}/api/+"
	topic := self.Config.Mqtt.APISub
	clientId, _, _ := self.GetConnectInfoByUid()
	apisub := strings.Replace(topic, "{{clientId}}", clientId, -1)
	log.Println("api 监听频道", apisub)
	self.Base.MqttSub(apisub, func(topic string, msg []byte) {
		log.Println("mqtt收到api调用", topic, string(msg))
		//resp_topic := string(topic) + "/response"
		resp_topic := string(topic) + self.Config.Mqtt.RespTail
		err, js := self.apiBridge(msg)
		if err != nil {
			log.Println(err)
			re := Result{"-1", nil, err.Error()}
			b, _ := json.Marshal(re)
			self.Base.MqttPub(resp_topic, b)
			return
		}
		log.Println("接收返回:", string(js))
		self.Base.MqttPub(resp_topic, js)
	})
}

//通过mqtt请求调用api,返回调用api后的json
/*
/d0e32f3d/api/22
{
	"method":"GET",
	"url":"/mqtt/info",
	"body":{}
}
*/
func (self *Client) apiBridge(msg []byte) (error, []byte) {
	req := &common.ApiRequset{}
	err := json.Unmarshal(msg, req)
	if err != nil {
		return err, []byte{}
	}
	url := "http://127.0.0.1:" + self.httpBridgePort
	log.Println(url)
	switch req.Method {
	case "GET":
		{
			log.Println(req)
			_, bodyBytes, err := gorequest.New().Timeout(5 * time.Second).Get(url + req.Url).EndBytes()
			if err != nil {
				return err[0], []byte(err[0].Error())
			}
			return nil, bodyBytes
		}
	case "POST":
		{
			_, bodyBytes, err := gorequest.New().Timeout(5 * time.Second).
				Post(url + req.Url).
				Send(req.Body).
				EndBytes()
			if err != nil {
				return err[0], []byte(err[0].Error())
			}
			return nil, bodyBytes
		}
	case "DELETE":
		{
			_, bodyBytes, err := gorequest.New().Timeout(5 * time.Second).
				Delete(url + req.Url).
				Send(req.Body).
				EndBytes()
			if err != nil {
				return err[0], []byte(err[0].Error())
			}
			return nil, bodyBytes
		}
	case "PUT":
		{
			_, bodyBytes, err := gorequest.New().Timeout(5 * time.Second).
				Put(url + req.Url).
				Send(req.Body).
				EndBytes()
			if err != nil {
				return err[0], []byte(err[0].Error())
			}
			return nil, bodyBytes
		}
	case "PATCH":
		{
			_, bodyBytes, err := gorequest.New().Timeout(5 * time.Second).
				Patch(url + req.Url).
				Send(req.Body).
				EndBytes()
			if err != nil {
				return err[0], []byte(err[0].Error())
			}
			return nil, bodyBytes
		}
	default:
		{
			return errors.New("不是http方法"), []byte{}
		}

	}
}
